package cn.virens.mybatis.page;

import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;

public class PageParamUtil {

	public static Object criteriaEqual(Map<String, Object> param, String key) {
		return PageParamUtil.criteriaEqual(param, key, null);
	}

	public static Object criteriaEqual(Map<String, Object> param, String key, Object def) {
		return param == null ? def : param.get(key);
	}

	public static String criteriaLike(Map<String, Object> param, String key) {
		return PageParamUtil.criteriaLike(param, key, null);
	}

	public static String criteriaLike(Map<String, Object> param, String key, String def) {
		Object val = PageParamUtil.criteriaEqual(param, key, def);

		if (val != null && !"".equals(val)) {
			return "%" + val + "%";
		} else {
			return null;
		}
	}

	public static Iterable<Object> criteriaIn(Map<String, Object> param, String key) {
		return PageParamUtil.criteriaIn(param, key, null);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Iterable<Object> criteriaIn(Map<String, Object> param, String key, Object def) {
		Object val = PageParamUtil.criteriaEqual(param, key, def);

		if (val != null && ArrayUtil.isArray(val)) {
			return n(Arrays.asList((Object[]) val));
		} else if (val instanceof Collection) {
			return n((Collection<Object>) val);
		} else if (val instanceof Map) {
			return n(((Map) val).values());
		} else if (val != null) {
			return n(Arrays.asList(val));
		} else {
			return null;
		}
	}

	private static Iterable<Object> n(Iterable<Object> answer) {
		return CollUtil.isNotEmpty(answer) ? answer : null;
	}
}
